package com.xhwl.centiotdata.suppliersystem.eesd.ntelroom;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xhwl.centiotdata.mq.producer.GeneralProducer;
import com.xhwl.centiotdata.pojo.dto.eesd.EesdConfigDTO;
import com.xhwl.centiotdata.service.cent.ICentAlarmService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.cent.IEesdCentService;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.centiotdata.utils.ThreadPoolExecutorService;
import com.xhwl.common.constant.cent.alarm.AlarmConstant;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.iotdata.ntelroom.NtDeviceStatusPullRespDTO;
import com.xhwl.common.dto.cent.iotdata.ntescar.NtEsCarPullRespDTO;
import com.xhwl.common.enums.device.DeviceOnlineStatusEnum;
import com.xhwl.common.enums.device.DeviceTypeEnum;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.cent.alarm.AlarmLog;
import com.xhwl.common.pojo.cent.alarm.AlarmManagement;
import com.xhwl.common.pojo.cent.device.Device;
import com.xhwl.common.pojo.cent.energy.*;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.utils.ChkUtil;
import com.xhwl.common.utils.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * 南投储能车
 */
@RestController
@Slf4j
public class NtElRoomApiHandler {
    /**
     * 接口为增量，第一次拉去默认从20秒前的数据获取
     */
    private static final int DEFAULT_PERIOD = 20 * 1000;
    private static final int REQUEST_RECORD_COUNT = 2000;
    private static final String LAST_TIMESTAMP_KEY_PREFIX = "NT_ELROOM_LAST_TIMESTAMP_";
    private static final String NT_TOKEN_KEY = "NT_TOKEN_KEY";
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private IEesdCentService iEesdCentService;
    @Autowired
    private IDeviceCentService iDeviceCentService;
    @Autowired
    private GeneralProducer generalProducer;
    @Autowired
    public ICentAlarmService centAlarmService;

    /**
     * 拉取数据，最新的一条
     */
    @PostMapping("/ntelroom/pullRecordTenSeconds")
    public void pullEnvData(@RequestBody EesdConfigDTO eesdConfigDTO) {
        if (eesdConfigDTO.getProjectId() == null || eesdConfigDTO.getNtEsCar() == null) {
            log.warn("pull[南投电房]实时数据配置有误");
            return;
        }
        List<EesdConfigDTO.NtElRoom> ntElRooms = eesdConfigDTO.getNtElRoom();
        String token;
        if (redisUtils.get(NT_TOKEN_KEY) != null) {
            token = redisUtils.get(NT_TOKEN_KEY).toString();
        } else {
            token = getToken(eesdConfigDTO.getNtEsCar());
        }
        ntElRooms.forEach(room -> {
            //CountDownLatch countdownLatch = new CountDownLatch(4);
            List<EnergyRoomTempAndHumidityDevice> tempAndHumidityDevices = new ArrayList<>();
            List<EnergyRoomOxygenDevice> oxygenDevices = new ArrayList<>();
            List<EnergyRoomShuntDevice> roomShuntDevices = new ArrayList<>();
            List<EnergyRoomElectricMeter> electricMeters = new ArrayList<>();
            List<AlarmManagement> alarmManagements = new ArrayList<>();

            log.info("开始同步的房间信息为：{},token:{}", room, token);
            //获取电房设备信息
            EnergyRoomDeviceDTO elRoomDevice = listEnergyRoomDevices(eesdConfigDTO.getProjectId(), room.getOrganizationId());
            List<DeviceDTO> wdDevices = elRoomDevice.getWdDevice();//温湿度传感器
            List<DeviceDTO> yqDevices = elRoomDevice.getYqDevice();//氧气传感器
            List<DeviceDTO> flDevices = elRoomDevice.getFlDevice();//分励装置
            List<DeviceDTO> dbDevices = elRoomDevice.getDbDevice();//电表

            //电房温湿度处理
            //  ThreadPoolExecutorService.getThreadPool().submit(() -> {

            wdDevices.forEach(wdDevice -> {
                try {
                    EnergyRoomTempAndHumidityDevice tempAndHumidityDevice = new EnergyRoomTempAndHumidityDevice();
                    tempAndHumidityDevice.setProjectId(eesdConfigDTO.getProjectId());
                    tempAndHumidityDevice.setAddressId(room.getOrganizationId());
                    tempAndHumidityDevice.setAddressName(room.getRoomName());
                    tempAndHumidityDevice.setDeviceId(wdDevice.getThirdDeviceId());
                    tempAndHumidityDevice.setDeviceName(wdDevice.getName());
                    tempAndHumidityDevice.setCentDeviceId(wdDevice.getId());
                    NtEsCarPullRespDTO respDTO = pullNewByEquipment(eesdConfigDTO, wdDevice, token);
                    if (respDTO != null && respDTO.getData() != null) {
                        tempAndHumidityDevice = convertToRoomTempAndHumidityDetail(tempAndHumidityDevice, respDTO);
                        List<AlarmManagement> alarmManagementList = handlerRoomAlarmDetail(eesdConfigDTO.getProjectId(), wdDevice.getId(), respDTO);
                        alarmManagements.addAll(alarmManagementList);
                        tempAndHumidityDevices.add(tempAndHumidityDevice);
                    }
                } catch (Exception e) {
                    log.info(e.getMessage());
                }
            });


            //});

            //电房氧气度处理
            /*ThreadPoolExecutorService.getThreadPool().submit(() -> {*/
            yqDevices.forEach(yqDevice -> {
                try {
                    EnergyRoomOxygenDevice oxygenDevice = new EnergyRoomOxygenDevice();
                    oxygenDevice.setProjectId(eesdConfigDTO.getProjectId());
                    oxygenDevice.setAddressId(room.getOrganizationId());
                    oxygenDevice.setAddressName(room.getRoomName());
                    oxygenDevice.setDeviceId(yqDevice.getThirdDeviceId());
                    oxygenDevice.setDeviceName(yqDevice.getName());
                    oxygenDevice.setCentDeviceId(yqDevice.getId());
                    NtEsCarPullRespDTO respDTO = pullNewByEquipment(eesdConfigDTO, yqDevice, token);
                    if (respDTO != null && respDTO.getData() != null) {
                        oxygenDevice = convertToRoomOxygenDetail(oxygenDevice, respDTO);
                        oxygenDevices.add(oxygenDevice);
                    }
                } catch (Exception e) {
                    log.info(e.getMessage());
                }
            });

            /* });*/

            //分励装置处理 告警字段
            //ThreadPoolExecutorService.getThreadPool().submit(() -> {
            flDevices.forEach(elDevice -> {
                try {
                    EnergyRoomShuntDevice shuntDevice = new EnergyRoomShuntDevice();
                    NtEsCarPullRespDTO respDTO = pullNewByEquipment(eesdConfigDTO, elDevice, token);
                    if (respDTO != null && respDTO.getData() != null) {
                        shuntDevice.setProjectId(eesdConfigDTO.getProjectId());
                        shuntDevice.setAddressId(room.getOrganizationId());
                        shuntDevice.setAddressName(room.getRoomName());
                        shuntDevice.setDeviceId(elDevice.getThirdDeviceId());
                        shuntDevice.setDeviceName(elDevice.getName());
                        shuntDevice.setCentDeviceId(elDevice.getId());
                        shuntDevice = convertToRoomFlDeviceDetail(shuntDevice, respDTO);
                        roomShuntDevices.add(shuntDevice);
                        //告警字段设备id 为设备中台设备ID
                        List<AlarmManagement> alarmManagementList = handlerRoomAlarmDetail(eesdConfigDTO.getProjectId(), elDevice.getId(), respDTO);
                        alarmManagements.addAll(alarmManagementList);
                    }
                } catch (Exception e) {
                    log.info("拉取分励装置数据异常{}", e.getMessage());
                }
            });

            //  });

            //电表数据处理
            //ThreadPoolExecutorService.getThreadPool().submit(() -> {

            log.info("处理房间：{}，设备数量：{}", room.getRoomName(), dbDevices.size());
            dbDevices.forEach(dbDevice -> {
                try {
                    EnergyRoomElectricMeter electricMeter = new EnergyRoomElectricMeter();
                    NtEsCarPullRespDTO respDTO = pullNewByEquipment(eesdConfigDTO, dbDevice, token);
                    if (respDTO != null && respDTO.getData() != null) {
                        electricMeter.setProjectId(eesdConfigDTO.getProjectId());
                        electricMeter.setAddressId(room.getOrganizationId());
                        electricMeter.setAddressName(room.getRoomName());
                        electricMeter.setDeviceId(dbDevice.getThirdDeviceId());
                        electricMeter.setDeviceName(dbDevice.getName());
                        electricMeter.setCentDeviceId(dbDevice.getId());
                        electricMeter = convertToRoomDbDeviceDetail(electricMeter, respDTO);
                        electricMeters.add(electricMeter);
                    }
                } catch (Exception e) {
                    log.info("拉取电表设备数据异常{}", e.getMessage());
                }
            });

            //  });

            //try {
            //countdownLatch.await();
            //同步数据
            log.info("tempAndHumidityDevices.size():{},--oxygenDevices.size():{},--roomShuntDevices.size():{},--electricMeters.size():{},--alarmManagements.size)_:{}",
                    tempAndHumidityDevices.size(), oxygenDevices.size(), roomShuntDevices.size(), electricMeters.size(), alarmManagements.size());
            if (tempAndHumidityDevices.size() > 0) {
                log.info("开始同步数据到eesd-温湿度");
                iEesdCentService.roomWsdDetailSync(tempAndHumidityDevices);
            }
            if (oxygenDevices.size() > 0) {
                log.info("开始同步数据到eesd-氧气");
                iEesdCentService.roomOxygenDetailSync(oxygenDevices);
            }
            if (roomShuntDevices.size() > 0) {
                log.info("开始同步数据到eesd-分励装置");
                iEesdCentService.roomFlDetailSync(roomShuntDevices);
            }
            if (electricMeters.size() > 0) {
                log.info("开始同步数据到eesd-电表,数量{}", electricMeters.size());
                iEesdCentService.roomDbDetailSync(electricMeters);
            }

            //发送告警数据
            for (AlarmManagement alarmManagement : alarmManagements) {
                AlarmLog alarmLog = new AlarmLog();
                alarmLog.setPushTime(new Date());
                alarmLog.setContent(JSONObject.toJSONString(alarmManagement));
                alarmLog.setTag("nt-room");
                centAlarmService.insert(alarmLog);
                generalProducer.send(AlarmConstant.DAHUA_ALARM_TOPIC, alarmManagement);
            }
            /*} catch (InterruptedException e) {
                e.printStackTrace();
            }*/
        });
    }

    @PostMapping("/ntelroom/pullRecordTenMinutes")
    public void pullRecord(@RequestBody EesdConfigDTO eesdConfigDTO) {
        if (eesdConfigDTO.getProjectId() == null || eesdConfigDTO.getNtEsCar() == null) {
            log.warn("pull[南投电房]实时数据配置有误");
            return;
        }
        String token;
        if (redisUtils.get(NT_TOKEN_KEY) != null) {
            token = redisUtils.get(NT_TOKEN_KEY).toString();
        } else {
            token = getToken(eesdConfigDTO.getNtEsCar());
        }
        try {
            log.info("开始同步设备状态-----");
            List<Integer> addressIds = eesdConfigDTO.getNtElRoom().stream().map(e -> e.getOrganizationId()).collect(Collectors.toList());
            DevicePageQuery deviceQuery = new DevicePageQuery();
            deviceQuery.setOrganizationIdList(addressIds);
            List<Device> updateDeviceList = new ArrayList<>();
            List<DeviceDTO> deviceDTOList = iDeviceCentService.listDevice(null, deviceQuery);
            if (!CollectionUtils.isEmpty(deviceDTOList)) {
                List<NtDeviceStatusPullRespDTO> deviceStatusList = pullDeviceStatus(eesdConfigDTO, token);
                deviceStatusList.forEach(deviceStatus -> {
                    deviceDTOList.forEach(deviceDTO -> {
                        if (deviceDTO.getThirdDeviceId().equals(deviceStatus.getEquipmentId())) {
                            Device device = new Device();
                            device.setThirdDeviceId(deviceStatus.getEquipmentId());
                            device.setOnlineStatus(deviceStatus.getStatus().equals("online") ? DeviceOnlineStatusEnum.ONLINE : DeviceOnlineStatusEnum.OFFLINE);
                            updateDeviceList.add(device);
                        }
                    });

                });
                if (!CollectionUtils.isEmpty(updateDeviceList)) {
                    log.info("-----------开始更新设备状态");
                    iDeviceCentService.batchUpdateStatus(updateDeviceList);
                }
                log.info("pull[南投电房]设备状态完毕");
            }
        } catch (Exception e) {
            log.info("同步电房设备状态异常：{}", e.getMessage());
        }


        //环境检测仪处理
        try {
            log.info("环境检测仪处理----");
            EnergyGrowatEnvironment energyGrowatEnvironment = new EnergyGrowatEnvironment();
            energyGrowatEnvironment.setProjectId(eesdConfigDTO.getProjectId());
            energyGrowatEnvironment.setDeviceId(eesdConfigDTO.getThirdDeviceId());
            energyGrowatEnvironment.setCentDeviceId(eesdConfigDTO.getDeviceId());
            DeviceDTO deviceDTO = new DeviceDTO();
            deviceDTO.setProjectId(eesdConfigDTO.getProjectId());
            deviceDTO.setId(Integer.valueOf(eesdConfigDTO.getDeviceId()));
            deviceDTO.setThirdDeviceId(eesdConfigDTO.getThirdDeviceId());
            NtEsCarPullRespDTO respDTO = pullNewByEquipment(eesdConfigDTO, deviceDTO, token);
            energyGrowatEnvironment = convertToGrowatEnvironmentDetail(energyGrowatEnvironment, respDTO);
            if (energyGrowatEnvironment != null) {
                iEesdCentService.growatEnvironmentDetailSync(energyGrowatEnvironment);
            }
        } catch (Exception e) {
            log.info("同步环境检测仪：{}", e.getMessage());
        }
    }

    /**
     * 获取电房设备
     */
    private EnergyRoomDeviceDTO listEnergyRoomDevices(Integer projectId, Integer organizationId) {
        DevicePageQuery deviceQuery = new DevicePageQuery();
        deviceQuery.setProjectId(projectId);
        if (!ObjectUtils.isEmpty(organizationId)) {
            deviceQuery.setOrganizationId(organizationId);
        }
        deviceQuery.setDeviceTypeIdList(Arrays.asList(DeviceTypeEnum.WATT_HOUR_METER.getCode()
                , DeviceTypeEnum.NFDW_ROOM_SHUNT_DEVICE.getCode()
                , DeviceTypeEnum.NFDW_ROOM_PARTIAL_DISCHARGE.getCode()
                , DeviceTypeEnum.NFDW_ROOM_TEMP_SENSOR.getCode()
                , DeviceTypeEnum.NFDW_ROOM_SMOKE_SENSOR.getCode()
                , DeviceTypeEnum.NFDW_ROOM_OXYGEN_SENSOR.getCode()
                , DeviceTypeEnum.NFDW_ROOM_THE_BARTENDER.getCode()
                , DeviceTypeEnum.NFDW_ROOM_GNDLTWD.getCode()
                , DeviceTypeEnum.NFDW_ROOM_KGGDLTCW.getCode()

        ));

        List<DeviceDTO> deviceDTOS = iDeviceCentService.listDevice(null, deviceQuery);
        if (CollectionUtils.isEmpty(deviceDTOS)) {
            return new EnergyRoomDeviceDTO();
        }
        //设备类型拆
        EnergyRoomDeviceDTO deviceDTO = new EnergyRoomDeviceDTO();
        deviceDTO.setDbDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.WATT_HOUR_METER.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setFlDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_SHUNT_DEVICE.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setJfDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_PARTIAL_DISCHARGE.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setWdDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_TEMP_SENSOR.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setYgDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_SMOKE_SENSOR.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setYqDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_OXYGEN_SENSOR.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setJbDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_THE_BARTENDER.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setGndltwdDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_GNDLTWD.getCode())).collect(Collectors.toList())
        );
        deviceDTO.setMhcwDevice(
                deviceDTOS.stream().filter(device -> (device.getDeviceTypeId()).equals(DeviceTypeEnum.NFDW_ROOM_KGGDLTCW.getCode())).collect(Collectors.toList())
        );
        return deviceDTO;

    }

    /**
     * 只需要最新的一条
     */
    private NtEsCarPullRespDTO pullNewByEquipment(EesdConfigDTO eesdConfigDTO, DeviceDTO carDevice, String token) {
        String lastTimeStamp = getLastTimeStamp(eesdConfigDTO.getProjectId(), carDevice.getId());
        JSONObject preJson = null;
        JSONObject currJson = null;
        Integer retureRecordCount = 0;
        do {
            preJson = currJson;
            currJson = pullByEquipment(eesdConfigDTO.getNtEsCar(), carDevice.getThirdDeviceId(), lastTimeStamp, "/app/v1.0/equipment/data/pullByEquipment", token);
            retureRecordCount = currJson.getInteger("RetureRecordCount");
            lastTimeStamp = currJson.getString("maxTimeStamp");
        } while (retureRecordCount >= REQUEST_RECORD_COUNT);
        NtEsCarPullRespDTO resp = null;
        if (retureRecordCount > 0) {
            JSONArray dataList = currJson.getJSONArray("dataList");
            List<NtEsCarPullRespDTO> list = dataList.toJavaList(NtEsCarPullRespDTO.class);
            resp = list.get(list.size() - 1);
        } else if (preJson != null) {
            JSONArray dataList = preJson.getJSONArray("dataList");
            if (dataList != null) {
                List<NtEsCarPullRespDTO> list = dataList.toJavaList(NtEsCarPullRespDTO.class);
                resp = list.get(list.size() - 1);
            }
        }
        //更新最大时间戳
        updateLastTimeStamp(eesdConfigDTO.getProjectId(), carDevice.getId(), lastTimeStamp);
        return resp;
    }

    private List<NtDeviceStatusPullRespDTO> pullDeviceStatus(EesdConfigDTO eesdConfigDTO, String token) {
        String lastTimeStamp = getLastTimeStamp(eesdConfigDTO.getProjectId(), -1);
        JSONObject preJson = null;
        JSONObject currJson = null;
        Integer retureRecordCount = 0;
        do {
            preJson = currJson;
            currJson = pullByEquipment(eesdConfigDTO.getNtEsCar(), null, lastTimeStamp, "/app/v1.0/equipment/status/pull", token);
            retureRecordCount = currJson.getInteger("RetureRecordCount");
            lastTimeStamp = currJson.getString("maxTimeStamp");
        } while (retureRecordCount >= REQUEST_RECORD_COUNT);
        List<NtDeviceStatusPullRespDTO> list = new ArrayList<>();
        if (retureRecordCount > 0) {
            JSONArray dataList = currJson.getJSONArray("dataList");
            list.addAll(dataList.toJavaList(NtDeviceStatusPullRespDTO.class));
        } else if (preJson != null) {
            JSONArray dataList = preJson.getJSONArray("dataList");
            if (dataList != null) {
                list.addAll(list = dataList.toJavaList(NtDeviceStatusPullRespDTO.class));
            }
        }
        //更新最大时间戳
        updateLastTimeStamp(eesdConfigDTO.getProjectId(), -1, lastTimeStamp);
        return list;
    }

    public static String getLastTimestampKey(Integer projectId, Integer deviceId) {
        return LAST_TIMESTAMP_KEY_PREFIX + projectId + "_" + deviceId;
    }

    private String getLastTimeStamp(Integer projectId, Integer deviceId) {
        //redis获取上次结束时间
        String lastTimestamp = (String) redisUtils.get(getLastTimestampKey(projectId, deviceId));
        if (lastTimestamp != null) {
            return lastTimestamp;
        }
        return ((System.currentTimeMillis() - DEFAULT_PERIOD) / 1000) + "-0";
    }

    private void updateLastTimeStamp(Integer projectId, Integer deviceId, Object maxTimeStamp) {
        //更新最大记录条数
        redisUtils.set(getLastTimestampKey(projectId, deviceId), maxTimeStamp);
    }


    private String getToken(EesdConfigDTO.NtEsCar ntEsCar) {
        String url = ntEsCar.getHost() + "/app/v1.0/session/token/apply";
        log.info("请求token-config:{}", ntEsCar);
        log.info("请求token-url:{}", url);
        Map<String, Object> map = Maps.newHashMap();
        map.put("appId", ntEsCar.getAppId());
        map.put("appSecret", ntEsCar.getAppSecret());
        map.put("scope", "all");
        //发起鉴权
        String result = HttpUtil.post(url, JSON.toJSONString(map), 3000);
        if (result == null) {
            throw new RuntimeException("result是null");
        }
        log.info("请求token-response:{}", result);
        Map<String, Object> res = JSON.parseObject(result, Map.class);
        if (res == null) {
            throw new RuntimeException(result);
        }
        if (ChkUtil.getInteger(res.get("errCode")) != 0) {
            throw new RuntimeException(result);
        }
        redisUtils.setWithMinute(NT_TOKEN_KEY, (String) res.get("token"), 120);
        return (String) res.get("token");
    }

    private JSONObject pullByEquipment(EesdConfigDTO.NtEsCar ntEsCar, String equipmentId, String lastTimeStamp, String path, String token) {
        String url = ntEsCar.getHost() + path;
        //log.info("请求-config:{}", ntEsCar);
        //log.info("请求-url:{}", url);
        Map<String, Object> map = Maps.newHashMap();
        if (StringUtils.isNotEmpty(equipmentId)) {
            map.put("equipmentId", equipmentId);
        }
        //时间戳+id
        map.put("lastTimeStamp", lastTimeStamp);
        map.put("requestRecordCount", REQUEST_RECORD_COUNT);
        log.info("请求-param:{}", JSON.toJSONString(map));
        String result = HttpRequest.post(url)
                .header("token", token)
                .body(JSON.toJSONString(map)).execute().body();
        if (result == null) {
            throw new RuntimeException("result是null");
        }
        // log.info("请求{}-response:{}", path, result);
        JSONObject respJson = JSONObject.parseObject(result);
        if (ChkUtil.getInteger(respJson.get("errCode")) != 0) {
            throw new RuntimeException(result);
        }
        return respJson;
    }


    /**
     * 电房温湿度
     *
     * @param tempAndHumidityDevice
     * @param respDTO
     * @return
     */
    private EnergyRoomTempAndHumidityDevice convertToRoomTempAndHumidityDetail(EnergyRoomTempAndHumidityDevice tempAndHumidityDevice, NtEsCarPullRespDTO respDTO) {
        Map<String, String> dataMap = JSONObject.parseObject(respDTO.getData(), Map.class);
        log.info(respDTO.getData());
        tempAndHumidityDevice.setHjwd(Double.valueOf(dataMap.getOrDefault("hjwd", "0")));
        tempAndHumidityDevice.setHjsd(Double.valueOf(dataMap.getOrDefault("hjsd", "0")));
        return tempAndHumidityDevice;
    }

    /**
     * 电房氧气
     *
     * @param oxygenDevice
     * @param respDTO
     * @return
     */
    private EnergyRoomOxygenDevice convertToRoomOxygenDetail(EnergyRoomOxygenDevice oxygenDevice, NtEsCarPullRespDTO respDTO) {
        Map<String, String> dataMap = JSONObject.parseObject(respDTO.getData(), Map.class);
        log.info(respDTO.getData());
        oxygenDevice.setHjyq(Double.valueOf(dataMap.getOrDefault("hjyq", "0")));
        return oxygenDevice;
    }

    /**
     * 环境质量检测仪
     *
     * @param growatEnvironment
     * @param respDTO
     * @return
     */
    private EnergyGrowatEnvironment convertToGrowatEnvironmentDetail(EnergyGrowatEnvironment growatEnvironment, NtEsCarPullRespDTO respDTO) {
        Map<String, Object> dataMap = JSONObject.parseObject(respDTO.getData(), Map.class);
        growatEnvironment.setQxwendu(Double.valueOf(dataMap.getOrDefault("qxwendu", "0").toString()));
        growatEnvironment.setQxzjwendu(Double.valueOf(dataMap.getOrDefault("qxzjwendu", "0").toString()));
        growatEnvironment.setQxshidu(Double.valueOf(dataMap.getOrDefault("qxshidu", "0").toString()));
        growatEnvironment.setQxfengsu(Double.valueOf(dataMap.getOrDefault("qxfengsu", "0").toString()));
        growatEnvironment.setQxfengxiang(Double.valueOf(dataMap.getOrDefault("qxfengxiang", "0").toString()));
        growatEnvironment.setQxyuliang(Double.valueOf(dataMap.getOrDefault("qxyuliang", "0").toString()));
        growatEnvironment.setQxspfushe(Double.valueOf(dataMap.getOrDefault("qxspfushe", "0").toString()));
        growatEnvironment.setQxqxfushe(Double.valueOf(dataMap.getOrDefault("qxqxfushe", "0").toString()));
        growatEnvironment.setQxssfushe(Double.valueOf(dataMap.getOrDefault("qxssfushe", "0").toString()));
        growatEnvironment.setQxzjfushe(Double.valueOf(dataMap.getOrDefault("qxzjfushe", "0").toString()));
        growatEnvironment.setQxspfushelj(Double.valueOf(dataMap.getOrDefault("qxspfushelj", "0").toString()));
        growatEnvironment.setQxqxfushelj(Double.valueOf(dataMap.getOrDefault("qxqxfushelj", "0").toString()));
        growatEnvironment.setQxssfushelj(Double.valueOf(dataMap.getOrDefault("qxssfushelj", "0").toString()));
        growatEnvironment.setQxzjfushelj(Double.valueOf(dataMap.getOrDefault("qxzjfushelj", "0").toString()));
        growatEnvironment.setQxrzshijian(Double.valueOf(dataMap.getOrDefault("qxrzshijian", "0").toString()));
        growatEnvironment.setQxdqyali(Double.valueOf(dataMap.getOrDefault("qxdqyali", "0").toString()));
        growatEnvironment.setQxshidu(Double.valueOf(dataMap.getOrDefault("qxshidu", "0").toString()));
        return growatEnvironment;
    }

    /**
     * 分励装置
     *
     * @param
     * @param respDTO
     * @return
     */
    private EnergyRoomShuntDevice convertToRoomFlDeviceDetail(EnergyRoomShuntDevice flDevice, NtEsCarPullRespDTO respDTO) {
        Map<String, Object> dataMap = JSONObject.parseObject(respDTO.getData(), Map.class);
        flDevice.setStatus(Integer.valueOf(dataMap.get("status").toString()));
        return flDevice;
    }

    /**
     * 电表
     *
     * @param
     * @param respDTO
     * @return
     */
    private EnergyRoomElectricMeter convertToRoomDbDeviceDetail(EnergyRoomElectricMeter electricMeter, NtEsCarPullRespDTO respDTO) {
        Map<String, String> dataMap = JSONObject.parseObject(respDTO.getData(), Map.class);
        electricMeter.setAxdy(Double.valueOf(dataMap.getOrDefault("axdy", "0")));
        electricMeter.setBxdy(Double.valueOf(dataMap.getOrDefault("bxdy", "0")));
        electricMeter.setCxdy(Double.valueOf(dataMap.getOrDefault("cxdy", "0")));
        electricMeter.setAxdl(Double.valueOf(dataMap.getOrDefault("axdl", "0")));
        electricMeter.setBxdl(Double.valueOf(dataMap.getOrDefault("bxdl", "0")));
        electricMeter.setCxdl(Double.valueOf(dataMap.getOrDefault("cxdl", "0")));
        electricMeter.setAglys(Double.valueOf(dataMap.getOrDefault("aglys", "0")));
        electricMeter.setBglys(Double.valueOf(dataMap.getOrDefault("bglys", "0")));
        electricMeter.setCglys(Double.valueOf(dataMap.getOrDefault("cglys", "0")));
        electricMeter.setYggl(Double.valueOf(dataMap.getOrDefault("yggl", "0")));
        electricMeter.setWggl(Double.valueOf(dataMap.getOrDefault("wggl", "0")));
        electricMeter.setAbxdy(Double.valueOf(dataMap.getOrDefault("abxdy", "0")));
        electricMeter.setAcxdy(Double.valueOf(dataMap.getOrDefault("acxdy", "0")));
        electricMeter.setBcxdy(Double.valueOf(dataMap.getOrDefault("bcxdy", "0")));
        electricMeter.setGlysz(Double.valueOf(dataMap.getOrDefault("glysz", "0")));
        electricMeter.setYggla(Double.valueOf(dataMap.getOrDefault("yggla", "0")));
        electricMeter.setYgglb(Double.valueOf(dataMap.getOrDefault("ygglb", "0")));
        electricMeter.setYgglc(Double.valueOf(dataMap.getOrDefault("ygglc", "0")));
        electricMeter.setWggla(Double.valueOf(dataMap.getOrDefault("wggla", "0")));
        electricMeter.setWgglb(Double.valueOf(dataMap.getOrDefault("wgglb", "0")));
        electricMeter.setWgglc(Double.valueOf(dataMap.getOrDefault("wgglc", "0")));
        electricMeter.setSzgla(Double.valueOf(dataMap.getOrDefault("szgla", "0")));
        electricMeter.setSzglb(Double.valueOf(dataMap.getOrDefault("szglb", "0")));
        electricMeter.setSzglc(Double.valueOf(dataMap.getOrDefault("szglc", "0")));
        electricMeter.setPl(Double.valueOf(dataMap.getOrDefault("pl", "0")));
        electricMeter.setSzglz(Double.valueOf(dataMap.getOrDefault("szglz", "0")));
        electricMeter.setDlhgq(Double.valueOf(dataMap.getOrDefault("dlhgq", "0")));
        electricMeter.setDyhgq(Double.valueOf(dataMap.getOrDefault("dyhgq", "0")));
        electricMeter.setZygdd(Double.valueOf(dataMap.getOrDefault("zygdd", "0")));
        electricMeter.setZwgdd(Double.valueOf(dataMap.getOrDefault("zwgdd", "0")));
        electricMeter.setZygglxl(Double.valueOf(dataMap.getOrDefault("zygglxl", "0")));
        electricMeter.setDybph(Double.valueOf(dataMap.getOrDefault("dybph", "0")));
        electricMeter.setDyxbzqbla(Double.valueOf(dataMap.getOrDefault("dyxbzqbla", "0")));
        electricMeter.setDyxbzqblb(Double.valueOf(dataMap.getOrDefault("dyxbzqblb", "0")));
        electricMeter.setDyxbzqblc(Double.valueOf(dataMap.getOrDefault("dyxbzqblc", "0")));
        electricMeter.setDlxbzqbla(Double.valueOf(dataMap.getOrDefault("dlxbzqbla", "0")));
        electricMeter.setDlxbzqblb(Double.valueOf(dataMap.getOrDefault("dlxbzqblb", "0")));
        electricMeter.setDlxbzqblc(Double.valueOf(dataMap.getOrDefault("dlxbzqblc", "0")));
        return electricMeter;
    }

    /**
     * 告警字段处理
     *
     * @param projectId
     * @param deviceId
     * @param respDTO
     * @return
     */
    private List<AlarmManagement> handlerRoomAlarmDetail(Integer projectId, Integer deviceId, NtEsCarPullRespDTO respDTO) {
        Map<String, Object> dataMap = JSONObject.parseObject(respDTO.getData(), Map.class);
        //处理电房告警字段
        Map<String, Object> warnField = new HashMap<>();
        if (dataMap.get("hjwd") != null) {
            warnField.put("WD", dataMap.get("hjwd"));
        }

        return createAlarmManagement(projectId, deviceId, warnField);

    }


    public List<AlarmManagement> createAlarmManagement(Integer projectId, Integer deviceId, Map<String, Object> map) {
        List<AlarmManagement> list = new ArrayList<>(map.size());
        map.forEach((key, value) -> {
            list.add(createAlarmManagement(projectId, deviceId, getAlarmInventoryCode(key, value), value));
        });
        return list;
    }

    public AlarmManagement createAlarmManagement(Integer projectId, Integer deviceId, String alarmInventoryCode, Object value) {
        AlarmManagement alarmManagement = new AlarmManagement();
        alarmManagement.setProjectId(projectId);
        alarmManagement.setDeviceId(deviceId);
        alarmManagement.setAlarmInventoryCode(alarmInventoryCode);
        alarmManagement.setAlarmTime(new Date());
        alarmManagement.setThreshold(new BigDecimal(value.toString()));
        return alarmManagement;
    }

    private String getAlarmInventoryCode(String key, Object value) {
        switch (key) {
            case "FL":
                //分励装置状态
                return "34674013";
            case "WD":
                //温度过高
                return "54213896";
            default:
                throw new DataException("暂不支持的状态");
        }
    }


    @Data
    public static class EnergyRoomDeviceDTO {
        private List<DeviceDTO> dbDevice;
        private List<DeviceDTO> flDevice;
        private List<DeviceDTO> jfDevice;
        private List<DeviceDTO> wdDevice;
        private List<DeviceDTO> ygDevice;
        private List<DeviceDTO> yqDevice;
        private List<DeviceDTO> jbDevice;
        private List<DeviceDTO> gndltwdDevice;
        private List<DeviceDTO> mhcwDevice;
    }
}
